var reportCtx = {
    tcOrgan: null, // 组织机构条件
    businessTypeSuggest: null, // 业务类型
    dimensionSuggest: null, // 维度
    dateSumTable: null, // 表格组件
    tableQueryKey: null,  // 服务器生成的queryKey，在导出时，需要回传服务器
    tableLastQueryString: null // 最后一次查询条件，在导出时，判断查询条件是否改变
};

$(function () {
    initStepTab();
    initExceptionType();
    initDateRange();
    initOrgan();
    initBusinessType();
    initDimension();
    initDateSumTable();
    initQueryButtonClick();
    initExportButtonClick();
});

// tab点击事件
function initStepTab(){
    var link = $("#link").val();
    $("#stepTab").children("li").removeClass("cur-li");
    $("#stepTab").children("li[value="+link+"]").addClass("cur-li");

    $("#stepTab").children("li").click(function() {
        var self = $(this);
        if(self.hasClass("cur-li")){
            return;
        }
        var tolink = self.attr("value");
        var dataSrc = self.attr("data-src");
        if(dataSrc){
            var data = {link: tolink};
            window.location = CONTEXT_PATH + dataSrc+ "?" + $.param(data, true);
        }
    });
}
function initExceptionCheck() {
    if($("#link").val()!=null) {
        var link = $("#link").val();
        var html="<label>指标：</label><label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='all' checked='checked'>全选</label>";
        switch (link){
            case "1":
            case "2":
            case "3":
                html+="<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='4' checked='checked'>超时未发</label>";
                break;
            case "4":
                html+="<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='5' checked='checked'>未及时签收</label>"
                    +"<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='6' checked='checked'>未及时上架</label>";
                break;
            case "5":
                html+="<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='7' checked='checked'>超15天未签收</label>"
                    +"<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='8' checked='checked'>超15天未上架</label>"
                    +"<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='9' checked='checked'>全程超履约(创建-签收)</label>"
                    +"<label class='checkbox-inline'><input name='exceptionType' type='checkbox' value='10' checked='checked'>全程超履约(创建-上架)</label>";
                break;
            default:
                break;
        }
        $("#exceptionTypeDiv").html(html);
    }
}
// 条件：指标点击事件
function initExceptionType() {
    initExceptionCheck();
    var $exceptionType = $("input[name='exceptionType']"); // 所有checkbox
    var $allItem = $exceptionType.filter("[value='all']"); // 全选checkbox
    $exceptionType.click(function () {
        var self = $(this);
        var myValue = self.val();
        var myChecked = self.attr("checked");
        if(myValue=="all"){ // 点击了全选
            if(myChecked){
                $exceptionType.attr("checked", myChecked);
            }else{
                $exceptionType.removeAttr("checked");
            }
        }else{ // 点击了其他选项
            if(myChecked){
                // 都选中了，才选中全选
                var notCheckedSize = $exceptionType.filter("[value!='all']").filter(":not(:checked)").size();
                if(notCheckedSize==0){
                    $allItem.attr("checked", myChecked);
                }
            }else{
                $allItem.removeAttr("checked");
            }
        }
    });
}

// 条件：日期范围
function initDateRange(){
    var dateObj = new Date();
    var endStr = DateUtil.formatDateTime(dateObj);
    dateObj.setHours(0);
    dateObj.setMinutes(0);
    dateObj.setSeconds(0);
    dateObj.setMilliseconds(0);
    dateObj.setTime(dateObj.getTime() - 86400000*7); // 减7天
    var startStr = DateUtil.formatDateTime(dateObj);

    laydate.render({
        elem: '#startDate',
        type: "datetime",
        value: startStr
    });
    laydate.render({
        elem: '#endDate',
        type: "datetime",
        value: endStr
    });
}

// 条件：组织机构
function initOrgan(){
    reportCtx.tcOrgan = new TcOrganCondition();
    reportCtx.tcOrgan.init();
}

// 条件：业务类型
function initBusinessType(){
    var businessTypeList = [];
    businessTypeList.push({id: "0", name: "TC送货"});
    businessTypeList.push({id: "1", name: "京东库房送货"});
    businessTypeList.push({id: "2", name: "供应商退货"});
    businessTypeList.push({id: "3", name: "其他"});
    businessTypeList.push({id: "4", name: "自营内配"});
    businessTypeList.push({id: "5", name: "商家内配"});
    businessTypeList.push({id: "6", name: "B2B"});
    businessTypeList.push({id: "7", name: "产地仓"});
    businessTypeList.push({id: "8", name: "虚拟子单（产地仓）"});
    businessTypeList.push({id: "9", name: "自营外单"});
    businessTypeList.push({id: "10", name: "大件内配"});
    businessTypeList.push({id: "11", name: "虚拟子单（大件）"});
    businessTypeList.push({id: "12", name: "冷链内配"});
    businessTypeList.push({id: "13", name: "大件备件库流转"});
    businessTypeList.push({id: "14", name: "分拣订单"});
    businessTypeList.push({id: "15", name: "闪购退货"});
    businessTypeList.push({id: "16", name: "图书退货"});
    businessTypeList.push({id: "17", name: "普货内配"});
    businessTypeList.push({id: "18", name: "冷链TC"});
    businessTypeList.push({id: "19", name: "普货上门提货"});
    businessTypeList.push({id: "20", name: "退货上门"});
    businessTypeList.push({id: "21", name: "冷链退货"});
    businessTypeList.push({id: "22", name: "促销调整"});
    businessTypeList.push({id: "23", name: "虚拟子单（促销调整"});
    businessTypeList.push({id: "24", name: "差异找回"});
    businessTypeList.push({id: "25", name: "拒收退货"});
    businessTypeList.push({id: "26", name: "冷链上门提货"});
    reportCtx.businessTypeSuggest = $("#businessType").magicSuggest({
        editable: false,
        expandOnFocus: true,
        data: businessTypeList,
        mode: "local",
        valueField: "id",
        displayField: "name",
        placeholder: "业务类型",
        maxSelection: 10,
        maxSelectionRenderer: function () {}
    });
}

// 条件：维度
function initDimension(){
    var dimensionList = [];
    dimensionList.push({id: "1", name: "单"});
    dimensionList.push({id: "2", name: "包裹"});
    dimensionList.push({id: "3", name: "重量"});
    dimensionList.push({id: "4", name: "体积"});
    reportCtx.dimensionSuggest = $("#dimension").magicSuggest({
        editable: false,
        expandOnFocus: true,
        data: dimensionList,
        mode: "local",
        valueField: "id",
        displayField: "name",
        placeholder: "维度",
        maxSelection: 1,
        maxSelectionRenderer: function () {}
    });
}

// 表格
function initDateSumTable(){
    reportCtx.dateSumTable = new DateSumTable();
    reportCtx.dateSumTable.init();
    reportCtx.dateSumTable.dateSumClick = function (exceptionSum, bucketIndex) {
        // alert("导出明细!" + "name: " + exceptionSum.name + ", bucketIndex: " + bucketIndex);

        if(!reportCtx.tableQueryKey){
            alert("请查询后再导出！");
            return;
        }

        var param = {};
        var errMsg = createTableQueryParam(param);
        if(errMsg){
            alert(errMsg);
            return;
        }

        if(reportCtx.tableLastQueryString!=$.param(param,true)){
            alert("查询条件已变，请重新查询后再导出！");
            return;
        }

        param.queryKey = reportCtx.tableQueryKey;
        param.detailExceptionType = exceptionSum.code;
        if(bucketIndex=="all"){
            param.detailColumn = bucketIndex;
        }else{
            param.detailColumn = exceptionSum.bucketList[bucketIndex].day;
        }

        var exportDetailUrl = $("#exportDetailUrl").val();
        var url = CONTEXT_PATH + exportDetailUrl + "?" + $.param(param,true);
        $("#downloadFileIframe").attr("src", url);
    }
}

// 点击查询按钮
function initQueryButtonClick(){
    var $queryButton = $("#queryButton");
    $queryButton.on('click', function () {
        var param = {};
        var errMsg = createTableQueryParam(param);
        if(errMsg){
            alert(errMsg);
            return;
        }

        $queryButton.attr("disabled","disabled");
        $.ajax({
            url: CONTEXT_PATH + $queryButton.attr("data-src"),
            cache: false,
            data: param,
            type: "get",
            traditional :true,
            dataType: 'json',
            success: function(result){
                if(result.returnCode=="200"){
                    // 记录queryKey
                    reportCtx.tableQueryKey = result.meta;
                    // 记录lastQueryString
                    reportCtx.tableLastQueryString = $.param(param,true);
                    // 渲染报表
                    renderMainTable(result.data);
                }else{
                    alert(result.returnMsg);
                }
                $queryButton.removeAttr("disabled");
            }
        });
    });
}

// 点击导出按钮
function initExportButtonClick(){
    var $exportButton = $("#exportButton");
    $exportButton.on('click', function () {
        if(!reportCtx.tableQueryKey){
            alert("请查询后再导出！");
            return;
        }

        var param = {};
        var errMsg = createTableQueryParam(param);
        if(errMsg){
            alert(errMsg);
            return;
        }
        if(reportCtx.tableLastQueryString!=$.param(param,true)){
            alert("查询条件已变，请重新查询后再导出！");
            return;
        }

        param.queryKey = reportCtx.tableQueryKey;
        var exportSumUrl = $("#exportSumUrl").val();
        var url = CONTEXT_PATH + exportSumUrl + "?" + $.param(param,true);
        $("#downloadFileIframe").attr("src", url);
    });
}

// 查询条件设置到data中，如果验证条件出错，则返回错误信息
function createTableQueryParam(data){
    // 指标
    var exceptionTypes = [];
    $("input[name='exceptionType']:checked").each(function () {
        var typeVal = $(this).val();
        if(typeVal!="all"){
            exceptionTypes.push(typeVal);
        }
    });
    if(exceptionTypes.length==0){
        return "至少选择一个指标";
    }
    data.exceptionType = exceptionTypes;

    // 日期基准
    var dateType = $("input[name='dateType']:checked").val();
    if(!dateType){
        return "请选择日期基准";
    }
    data.dateType = dateType;

    // 开始、结束日期
    var startDateStr = $("#startDate").val();
    if(StringUtil.isEmpty(startDateStr)){
        return "请选择开始日期";
    }
    var minDate = new Date();
    minDate.setHours(0);
    minDate.setMinutes(0);
    minDate.setSeconds(0);
    minDate.setMilliseconds(0);
    var minLong = minDate.getTime() - 86400000*60; // 减30天
    var startLong = DateUtil.parse(startDateStr).getTime();
    if(startLong<minLong){
        return "开始日期应在60天内";
    }
    var endDateStr = $("#endDate").val();
    if(StringUtil.isEmpty(endDateStr)){
        return "请选择结束日期";
    }
    // 异常环节
    var link = $("#link").val();
    if(!StringUtil.isEmpty(link)){
        data.link = link;
    }

    var endLong = DateUtil.parse(endDateStr).getTime();
    if(startLong>=endLong){
        return "开始日期应小于结束日期";
    }
    var index = $.inArray("9", exceptionTypes) + $.inArray("10", exceptionTypes);
    if(!(link==5 && index < 0)) {
        if ((endLong - startLong) > (86400000 * 20)) {
          return "开始结束日期最大相差20天";
        }
    }else {
        if ((endLong - startLong) > (86400000 * 60)) {
            return "开始结束日期最大相差60天";
        }
    }
    var holdUp = $("#holdUp").val();
    if(!StringUtil.isEmpty(holdUp) && isNaN(holdUp)){
        return "滞留时长(小时)必须为整数";
    }
    if(!StringUtil.isEmpty(holdUp) && parseInt(holdUp)>720) {
        return "滞留时长(小时)最大输入720小时";
    }

    data.startTime = startDateStr;
    data.endTime = endDateStr;

    // 组织机构
    var orgId = reportCtx.tcOrgan.organOrgSuggest.getValue();
    if(orgId && orgId.length>0){
        data.orgId = orgId;
    }
    var siteCode = reportCtx.tcOrgan.organTcSuggest.getValue();
    if(siteCode && siteCode.length>0){
        data.node = siteCode;
    }

    // 业务类型
    var businessType = reportCtx.businessTypeSuggest.getValue();
    if(businessType && businessType.length>0){
        data.businessType = businessType;
    }

    // 维度
    var dimension = reportCtx.dimensionSuggest.getValue();
    if(!StringUtil.isEmpty(dimension)){
        data.dimension = dimension;
    }

    // 商家编码
    var traderCode = $("#traderCode").val();
    if(!StringUtil.isEmpty(traderCode)){
        data.traderCode = traderCode;
    }

    // 商家名称
    var traderName = $("#traderName").val();
    if(!StringUtil.isEmpty(traderName)){
        // 中文转码
        data.traderName = encodeURIComponent(traderName);
    }

    if(!StringUtil.isEmpty(holdUp)){
        data.holdUp = holdUp;
    }
    return null;
}

// 表格加载完后，绑定事件
function renderMainTable(dateSumJson){
    reportCtx.dateSumTable.render(dateSumJson);
}